/*
 * Supermodal v1.2.1
 *
 * Copyright (c) 2009 Matthew Batchelder (http://borkweb.com)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://borkweb.com/
 *
 * Depends:
 *	ui.dialog.js
 */
;(function($) {
	var box, box_selector, el, caption, master_selector, options = {}, url = {}, width, height, the_rel, modal_id, items;
	var img_preloader, img_next_preloader, img_prev_preloader;
	var img_gallery = [];

	$.fn.supermodal = function(options) {

		/***
		 * _init
		 *
		 * initializes the supermodal object
		 */
		function _init() {
			// merge the defaults with what is passed in
			options = $.extend($.fn.supermodal.defaults, options);
			
			// save the initial selector so that dialog boxes can reference it when re-applying supermodal
			master_selector = options.selector || $(this).selector;
			box_selector = '.' + options.modalClass;
		
			// is there already an supermodal on the page?
			if($(box_selector).size() == 0) {
				// nope!
				// add supermodal to the page and keep it hidden by default
				$('body').append('<div class="' + options.modalClass + '" style="display: none;"></div>');	
					
				// initialize the dialog box
				$(box_selector).dialog(options);
			}//end if
		
			box = $(box_selector);			
		}//end _init

		function _display_content(){
			box.dialog('option', 'width', width);
			box.dialog('option', 'height', height);

			// reposition the dialog into the center of the screen
			box.dialog('option', 'position', box.dialog('option', 'position'));
			box.dialog('open');
		}//end _display_content

		/***
		 * _gallery_init
		 *
		 * initializes a gallery
		 */
		function _gallery_init(){
			if(the_rel) {
				if(!img_gallery[the_rel]){
					img_gallery[the_rel] = [];
					
					items = $(el.selector).find('*[rel=' + the_rel +']');
					items.each(function(i){
						var the_ab = $(this).attr('modal_id');
						img_gallery[the_rel][the_ab] = {
							item: $(this),
							title: caption + ' (Image ' + (Number(the_ab) + 1) + ' of ' + items.size() + ')'
						};
					});
				}//end if
				
				box.dialog('option', 'title', img_gallery[the_rel][modal_id].title);
			}//end if
		}//end _gallery_init

		/***
		 * _image_loaded
		 *
		 * Adjusts preloaded image for display in supermodal.  The resizing of large images in this
		 *   function is based off of the code in Thickbox.
		 */
		function _image_loaded() {
			// dimension calculation based on code from fancybox by Janis Skarnelis
			var viewport = $.fn.supermodal.getViewport();
			var divisor = Math.min(Math.min(viewport[0] - 150, img_preloader.width) / img_preloader.width, Math.min(viewport[1] - 150, img_preloader.height) / img_preloader.height);
			var img_width = Math.round(divisor * img_preloader.width);
			var img_height = Math.round(divisor * img_preloader.height);

			width = ((Number(img_width) > width) ? Number(img_width) : width);
			height = (((Number(img_height) + 50) > height) ? (Number(img_height) + 50) : height);
			
			var content = '<div class="ab-gallery-container" style="position:relative;text-align:center;"><img src="' + url.full + '" width="' + img_width + '" height="'+ img_height +'" alt="'+ caption +'"/>';
			if(options.gallery){
				if(the_rel){
					content += '<a href="#" class="ui-state-default ab-gallery-nav ab-gallery-prev" style="display:none;padding:0.5em;position:absolute;top:0;left:0;"><span class="ui-icon ui-icon-seek-prev" style="display: inline-block;"></span> Prev</a>';
					content += '<a href="#" class="ui-state-default ui-widget-content ab-gallery-nav ab-gallery-next" style="display:none;padding:0.5em;position:absolute;top:0;right:0;">Next <span class="ui-icon ui-icon-seek-next" style="display: inline-block;"></span></a>';
				}//end if
			}//end if
			content += '</div>';
			
			box.html(content);
			
			box.mouseover(function(){
					$(this).find('.ab-gallery-nav').show();
			}).mouseout(function(){
					$(this).find('.ab-gallery-nav').hide();
			});
			
			$('.ab-gallery-container .ab-gallery-prev').click(function(){
				var nav = (modal_id <= 0) ? (items.size() - 1) : (modal_id - 1);
				items.eq(nav).click();
				return false;
			});
			$('.ab-gallery-container .ab-gallery-next').click(function(){
				var nav = (modal_id >= items.size() - 1) ? 0 : (modal_id + 1);
				items.eq(nav).click();
				return false;
			});
			
			_display_content();
		}//end _image_loaded

		/***
		 * _open_modal
		 *
		 * opens a modal window
		 */
		function _open_modal(){
			el = $(this);
			modal_id = Number(el.attr('modal_id'));
			the_rel = el.attr('rel');

			box.html('<div style="text-align:center;" class="throbber-container"><img src="' + options.throbber + '" class="throbber"></div>');

			caption = el.attr('title') || el.attr('alt') || '&nbsp;';
			
			box.dialog('option', 'title', caption);
			
			try{
				/****************************************************
				 * initialize URL data.
				 ****************************************************/
				var the_url = options.url || el.attr('href') || el.attr('src') || el.attr('action') || '';
				if(options.event == 'submit'){
					var form_data = el.serialize();
					the_url += (the_url.indexOf('?') !== -1) ? ('&' + form_data) : ('?' + form_data);
				}//end if
				_parse_url(the_url);

				width = url.params.width || options.width || options.minWidth;
				height = url.params.height || options.height || options.minHeight;

				/****************************************************
				 * detect which type of box to display
				 ****************************************************/
				if(url.type == 'image') {
					// if this is a gallery, figure out which is
					if(options.gallery) {
						_gallery_init();
					}//end if gallery
				
					// create a preload image
					img_preloader = new Image();

					$(img_preloader).unbind().bind('load', _image_loaded);
					
					img_preloader.src = url.full;

				}//end if
				else {
					if(url.params.inlineId) {
						box.html($('#' + url.params.inlineId).html());
					} else if(!url.params.PM_iframe && options.modalType != 'iframe' && document.domain == url.domain) {
						box.load(url.full);
					} else {	
						box.html(box.html() + '<iframe src="' + url.full + '" width="' + width + '" height="' + height + '" style="display:none;"></iframe>')
							.dialog('option', 'resizeStop', function(){
								box.find('iframe').attr('width', box.css('width'));
							});
						box.find('iframe').unbind().bind('load', function(){
							$(box_selector + ' .throbber-container').remove();
							$(this).show();
						});
					}//end else

					// reapply modal window to sub elements
					options.selector = master_selector;
					box.find(master_selector).supermodal(options);

					_display_content();
				}//end else
			} catch(e) {}//end try/catch
			return false;
		}//end _open_modal

		/***
		 * _parse_url
		 *
		 * parses a the given URL into parts
		 *   full:  full url
		 *   base:  the url sans query string
		 *   domain: the url's domain
		 *   type:  whether url is an image url or other
		 *   query_string: the full query string
		 *   params: the query string broken out into key/value pairs
		 *
		 * @param string $url The URL to parse
		 */
		function _parse_url($url) {
			url = { full: $url };
			
			// no url...return
			if(!url.full) return true;					
			
			url.base = (url.full.indexOf('?') !== -1) ? url.full.substr(0, url.full.indexOf('?')) : url.full;
			url.domain = (new RegExp("^(?:http://)?([^/]+)")).exec(url.full)[1];
			url.type = (url.base.toLowerCase().match(/\.jpg$|\.jpeg$|\.png$|\.gif$|\.bmp$/)) ? 'image' : 'other';
			
			url.query_string = url.full.split('?')[1]+"";
			
			url.params = {};
			var pairs = url.query_string.split('&');
			for(var i = 0; i < pairs.length; i++) {
				var pair = pairs[i].split('=');
				url.params[pair[0]] = pair[1];
			}//end for
			
			if(url.params.width) url.params.width = (url.params.width < options.minWidth) ? options.minWidth : url.params.width;
			if(url.params.height) url.params.height = (url.params.height < options.minHeight) ? options.minHeight : url.params.height;
		}//end _parse_url
	
		/***
		 * _throb
		 *
		 * displays a throbber
		 */
		function _throb(){

		}//end _throb
	
		_init();

		$(this.selector).live(options.event, _open_modal);

		// loop over the elements that are becoming supermodal triggers
		return this.each(function(modal_id) {
			// give all elements an identifier...used for image galleries
			$(this).attr('modal_id', modal_id);
		});//end this.each
	};//end fn

	/***
	 * $.fn.supermodal.getViewport
	 *      code from fancybox by Janis Skarnelis
	 *
	 * returns viewable area dimensions
	 */
	$.fn.supermodal.getViewport = function() {
		return [$(window).width(), $(window).height(), $(document).scrollLeft(), $(document).scrollTop() ];
	};
	
	$.fn.supermodal.defaults = {
		event: 'click',
		modalClass: 'supermodal',
		gallery: true,
		modalType: true,
		selector: '',
		throbber: 'images/throbber.gif',
		autoOpen: false,
		height: 300,
		minHeight: 150,
		minWidth: 150,
		modal: true,
		resizeable: false,
		width: 500,
		url: false
	};
})(jQuery);